/**
 * 
 */
package com.netflexitysolutions.amazonws.sdb.orm.internal.util;

import java.util.Comparator;

import com.netflexitysolutions.amazonws.sdb.orm.metadata.AttributeMetadata;
import com.netflexitysolutions.amazonws.sdb.orm.metadata.ItemMetadata;

/**
 * @author netflexity
 *
 */
public class GenericRecordComparator<T> implements Comparator<T> {
    
    private String[] propertyNames;
    private ItemMetadata metadata;
    
    /**
     * @param metadata
     * @param propertyNames
     */
    public GenericRecordComparator(ItemMetadata metadata, String ... propertyNames){
        this.metadata = metadata;
        this.propertyNames = propertyNames;
    }
    
    /**
	 * @return the metadata
	 */
	public ItemMetadata getMetadata() {
		return metadata;
	}

	/**
	 * @param metadata the metadata to set
	 */
	public void setMetadata(ItemMetadata metadata) {
		this.metadata = metadata;
	}

	/* (non-Javadoc)
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	public int compare(T o1, T o2) {
        for (int i = 0; i < propertyNames.length; i++){
        	AttributeMetadata attributeMetadata = metadata.getAttributeMetadataByName(propertyNames[i]);
        	if(attributeMetadata != null){
        		Comparable<Object> c1 = (Comparable<Object>)attributeMetadata.getFieldValue(o1);
                Comparable<Object> c2 = (Comparable<Object>)attributeMetadata.getFieldValue(o2);
	            if (c1 == null && c2==null){
	                return 0;
	            }
	            else if (c1 == null){
	                return 1;
	            }
	            else if (c2 == null){
	                return -1;
	            }
	            else{
	                if(c1.compareTo(c2) == 0){ // in case, column values are equal
	                    if (i < (propertyNames.length - 1)){
	                        continue;
	                    }
	                    return 0;
	                }
	                else{
	                    return c1.compareTo(c2);
	                }
	            }
        	}
        }
        return 0;
    }
}
